package com.banciyuan.bcywebview.biz.write.photoselecotor.pselector;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.util.BaseWatcher;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.AlbumModel;
import com.banciyuan.bcywebview.biz.write.photoselecotor.model.PhotoModel;
import com.banciyuan.bcywebview.biz.write.photoselecotor.pselector.decoration.PhotoDecoration;
import com.banciyuan.bcywebview.biz.write.photoselecotor.ui.AlbumAdapter;
import com.banciyuan.bcywebview.biz.write.photoselecotor.ui.PhotoPreviewActivity;
import com.banciyuan.bcywebview.biz.write.photoselecotor.util.AnimationUtil;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.string.StringUtil;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by squall on 2017/3/16.
 */

public class PhotoActivity extends BaseActivity implements BaseWatcher, View.OnClickListener {

    private static final int REQUEST_CAMERA = 1;
    private static final int REQUEST_PREVIEW = 2;

    private boolean single_mode;
    private int max_nums;

    private RecyclerView recyclerView;
    private PhotoAdapter mAdapter;
    private TextView cancel;
    private TextView preView;
    private TextView album;
    private View toolbar;

    private RelativeLayout layoutAlbum;
    private ListView ablumList;
    private AlbumAdapter albumAdapter;
    private TextView next;

    private List<PhotoModel> selected = new ArrayList<>();
    private List<PhotoModel> plist = new ArrayList<>();

    private PhotoHelper photoHelper;
    public String reccent_photo;
    private String selectedImagePath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pselector);
        initArgs();
        initUi();
        initAction();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        BaseObserver.getInstance().addWatcher(PhotoActivity.class, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        BaseObserver.getInstance().removeWatcher(PhotoActivity.class);
    }

    @Override
    protected void initArgs() {
        reccent_photo = getResources().getString(R.string.recent_photos);
        photoHelper = new PhotoHelper(this);
        Intent intent = getIntent();
        single_mode = intent.getBooleanExtra(gotoUtil.INTENT_VALUE_ONE, false);
        if (!single_mode && intent.getExtras() != null) {
            max_nums = intent.getIntExtra("key_max", 10);
            selected = (List<PhotoModel>) intent.getExtras().getSerializable("photos");
        }
    }

    @Override
    protected void initUi() {
        recyclerView = (RecyclerView) findViewById(R.id.gv_photos_ar);
        cancel = (TextView) findViewById(R.id.iv_back_vb);
        preView = (TextView) findViewById(R.id.tv_preview_ar);
        album = (TextView) findViewById(R.id.tv_album_ar);
        ablumList = (ListView) findViewById(R.id.lv_ablum_ar);
        toolbar = findViewById(R.id.layout_toolbar_ar);
        next = (TextView) findViewById(R.id.btn_right_lh);
        layoutAlbum = (RelativeLayout) findViewById(R.id.layout_album_ar);
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        recyclerView.addItemDecoration(new PhotoDecoration(UIUtils.dip2px(2, this)));

        mAdapter = new PhotoAdapter(this, plist, selected, single_mode);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(mAdapter);
        if (single_mode) {
            toolbar.setVisibility(View.GONE);
        } else {
            toolbar.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void initAction() {
        next.setOnClickListener(this);
        album.setOnClickListener(this);
        preView.setOnClickListener(this);

        findViewById(R.id.bv_back_lh).setOnClickListener(this);
        ablumList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AlbumModel current = (AlbumModel) parent.getItemAtPosition(position);
                for (int i = 0; i < parent.getCount(); i++) {
                    AlbumModel album = (AlbumModel) parent.getItemAtPosition(i);
                    if (null == album)
                        continue;
                    if (i == position)
                        album.setCheck(true);
                    else
                        album.setCheck(false);
                }
                albumAdapter.notifyDataSetChanged();
                hideAlbum();
                album.setText(current.getName());
                updatePhoto(current.getName());
            }
        });
    }

    protected void initData() {
        photoHelper.getReccent(new PhotoListener() {
            @Override
            public void onPhotoLoaded(List<PhotoModel> photos) {
                updateData(photos);
            }
        });

        photoHelper.updateAlbum(new AlbumListener() {
            @Override
            public void onAlbumLoaded(List<AlbumModel> photos) {
                if (albumAdapter != null) {
                    albumAdapter.notifyDataSetChanged();
                } else {
                    albumAdapter = new AlbumAdapter(PhotoActivity.this, (ArrayList<AlbumModel>) photos);
                    ablumList.setAdapter(albumAdapter);
                }
            }
        });
    }

    private void updatePhoto(String name) {
        if (!StringUtil.notNullEqual(name, reccent_photo)) {
            photoHelper.getAlbum(name, new PhotoListener() {
                @Override
                public void onPhotoLoaded(List<PhotoModel> photos) {
                    updateData(photos);
                }
            });
        } else {
            photoHelper.getReccent(new PhotoListener() {
                @Override
                public void onPhotoLoaded(List<PhotoModel> photos) {
                    updateData(photos);
                }
            });
        }
    }

    private void updateData(List<PhotoModel> photos) {
        plist.clear();
        plist.addAll(photos);
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter = new PhotoAdapter(PhotoActivity.this, plist, selected, single_mode);
            recyclerView.setAdapter(mAdapter);
        }
        recyclerView.scrollToPosition(0);
        setNext();
    }

    private void setNext() {
        if (selected != null && selected.size() == 0) {
            next.setVisibility(View.INVISIBLE);
        } else {
            next.setVisibility(View.VISIBLE);
        }
        next.setText((getString(R.string.next) + "(" + selected.size() + ")"));
    }

    @Override
    public void onEventHappen(int eventCode, String message, Object object) {
        switch (eventCode) {
            case BaseObserver.TAKE_PHOTO:
                goTakePhoto();
                break;
            case BaseObserver.PHOTO_PERVIEW:
                showPrePicture((Integer) object - 1);
                break;
            case BaseObserver.PHOTO_SELECT:
                ok(message);
                break;
            case BaseObserver.CHANGE_NUM:
                setNext();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_right_lh:
                ok();
                break;
            case R.id.tv_album_ar:
                album();
                break;
            case R.id.tv_preview_ar:
                priview();
                break;
            case R.id.bv_back_lh:
                finish();
                break;
        }
    }

    private void ok() {
        if (selected.isEmpty()) {
            setResult(RESULT_CANCELED);
        } else {
            Intent data = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable("photos", (Serializable) selected);
            data.putExtras(bundle);
            setResult(RESULT_OK, data);
        }
        finish();
    }

    private void ok(String photoPath) {
        Intent data = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("path", photoPath);
        data.putExtras(bundle);
        setResult(RESULT_OK, data);
        finish();
    }

    private void goTakePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = null;
        try {
            File dic = new File(ImageManager.getImageFile(this) + "DCIM/");
            file = new File(dic + "image" + new Date().getTime() + ".jpg");
            if (!dic.exists()) {
                dic.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Uri imgUri = Uri.fromFile(file);
        selectedImagePath = file.getAbsolutePath();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
        Intent wrapperIntent = Intent.createChooser(intent, null);
        startActivityForResult(wrapperIntent, REQUEST_CAMERA);
    }

    @Override
    public void onBackPressed() {
        if (layoutAlbum.getVisibility() == View.VISIBLE) {
            hideAlbum();
        } else
            super.onBackPressed();
    }

    private void album() {
        if (layoutAlbum.getVisibility() == View.GONE) {
            popAlbum();
        } else {
            hideAlbum();
        }
    }

    /**
     * 弹出相册列表
     */
    private void popAlbum() {
        layoutAlbum.setVisibility(View.VISIBLE);
        new AnimationUtil(getApplicationContext(), R.anim.translate_up_current)
                .setLinearInterpolator().startAnimation(layoutAlbum);
    }

    /**
     * 隐藏相册列表
     */
    private void hideAlbum() {
        new AnimationUtil(getApplicationContext(), R.anim.translate_down)
                .setLinearInterpolator().startAnimation(layoutAlbum);
        layoutAlbum.setVisibility(View.GONE);
    }

    private void priview() {
        if (selected != null && !selected.isEmpty()) {
            Bundle bundle = new Bundle();
            bundle.putSerializable("photos", (Serializable) selected);
            Intent intent = new Intent(this, PhotoPreviewActivity.class);
            intent.putExtras(bundle);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivityForResult(intent, REQUEST_PREVIEW);
        }
    }

    private void showPrePicture(int position) {
        Bundle bundle = new Bundle();
        bundle.putInt("position", position);
        bundle.putString("album", album.getText().toString());
        bundle.putSerializable("selectedphotos", (Serializable) selected);
        Intent intent = new Intent(this, PhotoPreviewActivity.class);
        intent.putExtras(bundle);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivityForResult(intent, REQUEST_PREVIEW);
    }

    private boolean over10m(String photoPath) {
        if (photoPath == null) return false;
        File file = new File(photoPath);
        return file.exists() && file.length() > 10 * 1024 * 1024;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
            if (single_mode) {
                ok(selectedImagePath);
            } else {
                if (!over10m(selectedImagePath)) {
                    PhotoModel photoModel = new PhotoModel(selectedImagePath, true);
                    selected.add(photoModel);
                } else {
                    MyToast.show(PhotoActivity.this, getString(R.string.over_10m));
                }
                ok();
            }
        } else if (requestCode == REQUEST_PREVIEW && resultCode == RESULT_OK) {
            if (data != null && data.getExtras() != null) {
                List<PhotoModel> templist = (List<PhotoModel>) data.getExtras().getSerializable("photos");

                List<PhotoModel> mergelist = new ArrayList<>();
                mergelist.addAll(selected);
                if (templist != null) {
                    mergelist.removeAll(templist);
                    templist.removeAll(selected);
                    selected.addAll(templist);
                    selected.removeAll(mergelist);
                }
                setNext();
                mAdapter.notifyDataSetChanged();
            }
        }
    }

}
